package com.boyinet.gateway.tools.controller

import com.jcraft.jsch.Channel
import com.jcraft.jsch.JSch
import com.jcraft.jsch.Session
import de.felixroske.jfxsupport.FXMLController
import de.felixroske.jfxsupport.GUIState
import javafx.fxml.FXML
import javafx.fxml.Initializable
import javafx.scene.control.Button
import javafx.scene.control.TextArea
import javafx.scene.control.TextField
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.javafx.JavaFx
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.net.URL
import java.util.*


@FXMLController
class IndexViewController : Initializable {

    @FXML
    lateinit var host: TextField

    @FXML
    lateinit var port: TextField

    @FXML
    lateinit var username: TextField

    @FXML
    lateinit var password: TextField

    @FXML
    lateinit var command: TextField

    @FXML
    lateinit var result: TextArea

    @FXML
    lateinit var connect: Button

    val jSch: JSch = JSch()

    var session: Session? = null

    var channel: Channel? = null


    override fun initialize(location: URL?, resources: ResourceBundle?) {
        GUIState.getStage().setOnCloseRequest {
            session?.disconnect()
            channel?.disconnect()
        }
    }

    fun onConnect() {
        if (session == null) {
            GlobalScope.launch(Dispatchers.IO) {
                session = jSch.getSession(username.text.toString(), host.text.toString(), port.text.toInt()).apply {
                    setConfig("StrictHostKeyChecking", "no")
                    setPassword(password.text.toString())
                    connect(3000)
                }
                channel = session!!.openChannel("shell")
                channel!!.connect(3000)
                withContext(Dispatchers.JavaFx) { connect.text = "断开" }
                val inputStream: InputStream? = channel!!.inputStream
                try {
                    //循环读取
                    val buffer = ByteArray(1024)
                    var i = 0
                    //如果没有数据来，线程会一直阻塞在这个地方等待数据。
                    while (inputStream?.read(buffer).also { i = it!! } != -1) {
                        withContext(Dispatchers.JavaFx) { result.appendText(String(buffer.copyOfRange(0, i))) }
                    }
                } finally {
                    //断开连接后关闭会话
                    session!!.disconnect()
                    channel!!.disconnect()
                    inputStream?.close()
                }
            }
        } else {
            channel?.disconnect()
            session?.disconnect()
            session = null
            connect.text = "连接"
        }
    }

    fun onRun() {
        transToSSH(channel, command.text.toString() + "\r")
    }

    fun onRun1() {
        transToSSH(
            channel,
            "sudo sed -i -e 's|jiaoquan();|//jiaoquan();|g' -e \"s|setInterval('jiaoquan()', 15000);|//setInterval('jiaoquan()', 15000);|g\" /var/www/html/index.php \r"
        )
    }

    fun onRun2() {
        transToSSH(channel, "sudo sed -i \"3a\\  \\\$txt='1';\" /var/www/html/loadjiaoquan.php\r")
    }

    fun onRun3() {
        transToSSH(channel, "sudo sed -i  -e 's|IfAutoUpdate();|//IfAutoUpdate();|g' /var/www/html/login.php\r")
    }

    fun onClear() {
        result.clear()
    }

    @Throws(IOException::class)
    private fun transToSSH(channel: Channel?, command: String) {
        if (channel != null) {
            val outputStream: OutputStream = channel.outputStream
            outputStream.write(command.toByteArray())
            outputStream.flush()
        }
    }
}